%matplotlib inline
import datashader as ds
import datashader.transfer_functions as tf
import datashader.glyphs
from datashader import reductions
from datashader.core import bypixel
from datashader.utils import lnglat_to_meters as webm, export_image
from datashader.colors import colormap_select, Greys9, viridis, inferno
import copy
from pyproj import Proj, transform
import numpy as np
import pandas as pd
import urllib
import json
import datetime
import plotly.offline as py
import plotly.graph_objs as go
import plotly.express as px
from plotly import tools
# from shapely.geometry import Point, Polygon, shape
# In order to get shapley, you'll need to run [pip install shapely.geometry] from your terminal
from functools import partial
from IPython.display import GeoJSON
py.init_notebook_mode()
For module 2 we'll be looking at techniques for dealing with big data. In particular binning strategies and the datashader library (which possibly proves we'll never need to bin large data for visualization ever again.)
To demonstrate these concepts we'll be looking at the PLUTO dataset put out by New York City's department of city planning. PLUTO contains data about every tax lot in New York City.
PLUTO data can be downloaded from here. Unzip them to the same directory as this notebook, and you should be able to read them in using this (or very similar) code. Also take note of the data dictionary, it'll come in handy for this assignment.
# Code to read in v17, column names have been updated (without upper case letters) for v18
# bk = pd.read_csv('PLUTO17v1.1/BK2017V11.csv')
# bx = pd.read_csv('PLUTO17v1.1/BX2017V11.csv')
# mn = pd.read_csv('PLUTO17v1.1/MN2017V11.csv')
# qn = pd.read_csv('PLUTO17v1.1/QN2017V11.csv')
# si = pd.read_csv('PLUTO17v1.1/SI2017V11.csv')
# ny = pd.concat([bk, bx, mn, qn, si], ignore_index=True)
ny = pd.read_csv('pluto_21v2.csv')
# Getting rid of some outliers
ny = ny[(ny['yearbuilt'] > 1850) & (ny['yearbuilt'] < 2020) & (ny['numfloors'] != 0)]
C:\Users\Richard\anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3165: DtypeWarning: Columns (19,20,22,24,26,63,64) have mixed types.Specify dtype option on import or set low_memory=False.
I'll also do some prep for the geographic component of this data, which we'll be relying on for datashader.
You're not required to know how I'm retrieving the lattitude and longitude here, but for those interested: this dataset uses a flat x-y projection (assuming for a small enough area that the world is flat for easier calculations), and this needs to be projected back to traditional lattitude and longitude.
# wgs84 = Proj("+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs")
# nyli = Proj("+proj=lcc +lat_1=40.66666666666666 +lat_2=41.03333333333333 +lat_0=40.16666666666666 +lon_0=-74 +x_0=300000 +y_0=0 +ellps=GRS80 +datum=NAD83 +to_meter=0.3048006096012192 +no_defs")
# ny['xcoord'] = 0.3048*ny['xcoord']
# ny['ycoord'] = 0.3048*ny['ycoord']
# ny['lon'], ny['lat'] = transform(nyli, wgs84, ny['xcoord'].values, ny['ycoord'].values)
# ny = ny[(ny['lon'] < -60) & (ny['lon'] > -100) & (ny['lat'] < 60) & (ny['lat'] > 20)]
#Defining some helper functions for DataShader
background = "black"
export = partial(export_image, background = background, export_path="export")
cm = partial(colormap_select, reverse=(background!="black"))
Binning is a common strategy for visualizing large datasets. Binning is inherent to a few types of visualizations, such as histograms and 2D histograms (also check out their close relatives: 2D density plots and the more general form: heatmaps.
While these visualization types explicitly include binning, any type of visualization used with aggregated data can be looked at in the same way. For example, lets say we wanted to look at building construction over time. This would be best viewed as a line graph, but we can still think of our results as being binned by year:
trace = go.Scatter(
# I'm choosing BBL here because I know it's a unique key.
x = ny.groupby('yearbuilt').count()['bbl'].index,
y = ny.groupby('yearbuilt').count()['bbl']
)
layout = go.Layout(
xaxis = dict(title = 'Year Built'),
yaxis = dict(title = 'Number of Lots Built')
)
fig = go.Figure(data = [trace], layout = layout)
fig.show()
Something looks off... You're going to have to deal with this imperfect data to answer this first question.
But first: some notes on pandas. Pandas dataframes are a different beast than R dataframes, here are some tips to help you get up to speed:
Hello all, here are some pandas tips to help you guys through this homework:
Indexing and Selecting: .loc and .iloc are the analogs for base R subsetting, or filter() in dplyr
Group By: This is the pandas analog to group_by() and the appended function the analog to summarize(). Try out a few examples of this, and display the results in Jupyter. Take note of what's happening to the indexes, you'll notice that they'll become hierarchical. I personally find this more of a burden than a help, and this sort of hierarchical indexing leads to a fundamentally different experience compared to R dataframes. Once you perform an aggregation, try running the resulting hierarchical datafrome through a reset_index().
Reset_index: I personally find the hierarchical indexes more of a burden than a help, and this sort of hierarchical indexing leads to a fundamentally different experience compared to R dataframes. reset_index() is a way of restoring a dataframe to a flatter index style. Grouping is where you'll notice it the most, but it's also useful when you filter data, and in a few other split-apply-combine workflows. With pandas indexes are more meaningful, so use this if you start getting unexpected results.
Indexes are more important in Pandas than in R. If you delve deeper into the using python for data science, you'll begin to see the benefits in many places (despite the personal gripes I highlighted above.) One place these indexes come in handy is with time series data. The pandas docs have a huge section on datetime indexing. In particular, check out resample, which provides time series specific aggregation.
Merging, joining, and concatenation: There's some overlap between these different types of merges, so use this as your guide. Concat is a single function that replaces cbind and rbind in R, and the results are driven by the indexes. Read through these examples to get a feel on how these are performed, but you will have to manage your indexes when you're using these functions. Merges are fairly similar to merges in R, similarly mapping to SQL joins.
Apply: This is explained in the "group by" section linked above. These are your analogs to the plyr library in R. Take note of the lambda syntax used here, these are anonymous functions in python. Rather than predefining a custom function, you can just define it inline using lambda.
Browse through the other sections for some other specifics, in particular reshaping and categorical data (pandas' answer to factors.) Pandas can take a while to get used to, but it is a pretty strong framework that makes more advanced functions easier once you get used to it. Rolling functions for example follow logically from the apply workflow (and led to the best google results ever when I first tried to find this out and googled "pandas rolling")
Google Wes Mckinney's book "Python for Data Analysis," which is a cookbook style intro to pandas. It's an O'Reilly book that should be pretty available out there.
After a few building collapses, the City of New York is going to begin investigating older buildings for safety. The city is particularly worried about buildings that were unusually tall when they were built, since best-practices for safety hadn’t yet been determined. Create a graph that shows how many buildings of a certain number of floors were built in each year (note: you may want to use a log scale for the number of buildings). Find a strategy to bin buildings (It should be clear 20-29-story buildings, 30-39-story buildings, and 40-49-story buildings were first built in large numbers, but does it make sense to continue in this way as you get taller?)
# Start your answer here, inserting more cells as you go along
ny['yearbuilt'] = ny['yearbuilt'].astype(int)
ny.info()
<class 'pandas.core.frame.DataFrame'> Int64Index: 810654 entries, 1 to 858187 Data columns (total 90 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 borough 810654 non-null object 1 block 810654 non-null int64 2 lot 810654 non-null int64 3 cd 810541 non-null float64 4 ct2010 810541 non-null float64 5 cb2010 808795 non-null float64 6 schooldist 810541 non-null float64 7 council 810541 non-null float64 8 zipcode 810533 non-null float64 9 firecomp 810538 non-null object 10 policeprct 810541 non-null float64 11 healthcenterdistrict 810541 non-null float64 12 healtharea 810541 non-null float64 13 sanitboro 810527 non-null float64 14 sanitdistrict 810527 non-null float64 15 sanitsub 810446 non-null object 16 address 810654 non-null object 17 zonedist1 810570 non-null object 18 zonedist2 17426 non-null object 19 zonedist3 122 non-null object 20 zonedist4 4 non-null object 21 overlay1 69646 non-null object 22 overlay2 151 non-null object 23 spdist1 94230 non-null object 24 spdist2 49 non-null object 25 spdist3 0 non-null float64 26 ltdheight 2216 non-null object 27 splitzone 810570 non-null object 28 bldgclass 810654 non-null object 29 landuse 810178 non-null float64 30 easements 810654 non-null float64 31 ownertype 19071 non-null object 32 ownername 810637 non-null object 33 lotarea 810654 non-null float64 34 bldgarea 810652 non-null float64 35 comarea 804859 non-null float64 36 resarea 804859 non-null float64 37 officearea 804859 non-null float64 38 retailarea 804859 non-null float64 39 garagearea 804859 non-null float64 40 strgearea 804859 non-null float64 41 factryarea 804859 non-null float64 42 otherarea 804859 non-null float64 43 areasource 810654 non-null float64 44 numbldgs 810654 non-null float64 45 numfloors 810654 non-null float64 46 unitsres 810631 non-null float64 47 unitstotal 810631 non-null float64 48 lotfront 810654 non-null float64 49 lotdepth 810654 non-null float64 50 bldgfront 810654 non-null float64 51 bldgdepth 810654 non-null float64 52 ext 788501 non-null object 53 proxcode 810654 non-null float64 54 irrlotcode 810654 non-null object 55 lottype 810654 non-null float64 56 bsmtcode 810654 non-null float64 57 assessland 810654 non-null float64 58 assesstot 810654 non-null float64 59 exempttot 810654 non-null float64 60 yearbuilt 810654 non-null int32 61 yearalter1 810654 non-null float64 62 yearalter2 810654 non-null float64 63 histdist 28619 non-null object 64 landmark 1206 non-null object 65 builtfar 810652 non-null float64 66 residfar 810654 non-null float64 67 commfar 810654 non-null float64 68 facilfar 810654 non-null float64 69 borocode 810654 non-null int64 70 bbl 810654 non-null float64 71 condono 8395 non-null float64 72 tract2010 810541 non-null float64 73 xcoord 810580 non-null float64 74 ycoord 810580 non-null float64 75 zonemap 810573 non-null object 76 zmcode 14279 non-null object 77 sanborn 810538 non-null object 78 taxmap 810538 non-null float64 79 edesignum 7464 non-null object 80 appbbl 86917 non-null float64 81 appdate 86917 non-null object 82 plutomapid 810654 non-null int64 83 firm07_flag 26320 non-null float64 84 pfirm15_flag 55690 non-null float64 85 version 810654 non-null object 86 dcpedited 26892 non-null object 87 latitude 810580 non-null float64 88 longitude 810580 non-null float64 89 notes 0 non-null float64 dtypes: float64(57), int32(1), int64(4), object(28) memory usage: 559.7+ MB
# creating bins based on log values
ny['log_floors'] = np.log(ny.numfloors)
min_floors = np.floor(ny.log_floors.min())
max_floors = np.ceil(ny.log_floors.max())
bins = np.unique(np.floor(np.exp(np.arange(min_floors, max_floors+1)))).astype(int)
ny['max_floor'] = bins[np.digitize(ny.numfloors,bins, right=True)].astype(int)
trace = go.Bar(
x = ny.groupby('max_floor').max_floor.count().index.astype(str),
y = np.log(ny.groupby('max_floor').max_floor.count()))
lab = go.Layout(
xaxis = dict(title = 'Maximum heights'),
yaxis = dict(title = 'Count(log) of heights')
)
fig = go.Figure(data = trace, layout=lab)
fig.show()
traces = []
for i in range(1,len(bins)):
subset = ny[ny['max_floor'] == bins[i]]
count = subset.groupby('yearbuilt').yearbuilt.count()
trace = go.Bar(
name = '<'+ str(bins[i]),
x = count.index,
y = np.log(count)
)
traces.append(trace)
lab = go.Layout(
xaxis = dict(title = 'Years'),
yaxis = dict(title = 'Count(log) of heights')
)
fig = go.Figure(data=traces, layout = lab)
fig.update_layout(barmode='stack')
fig.show()
Datashader is a library from Anaconda that does away with the need for binning data. It takes in all of your datapoints, and based on the canvas and range returns a pixel-by-pixel calculations to come up with the best representation of the data. In short, this completely eliminates the need for binning your data.
As an example, lets continue with our question above and look at a 2D histogram of YearBuilt vs NumFloors:
fig = go.FigureWidget(
data = [
go.Histogram2d(x=ny['yearbuilt'], y=ny['numfloors'], autobiny=False, ybins={'size': 1}, colorscale='Greens')
]
)
fig
This shows us the distribution, but it's subject to some biases discussed in the Anaconda notebook Plotting Perils.
Here is what the same plot would look like in datashader:
#Defining some helper functions for DataShader
background = "black"
export = partial(export_image, background = background, export_path="export")
cm = partial(colormap_select, reverse=(background!="black"))
cvs = ds.Canvas(800, 500, x_range = (ny['yearbuilt'].min(), ny['yearbuilt'].max()),
y_range = (ny['numfloors'].min(), ny['numfloors'].max()))
agg = cvs.points(ny, 'yearbuilt', 'numfloors')
view = tf.shade(agg, cmap = cm(Greys9), how='log')
export(tf.spread(view, px=2), 'yearvsnumfloors')
That's technically just a scatterplot, but the points are smartly placed and colored to mimic what one gets in a heatmap. Based on the pixel size, it will either display individual points, or will color the points of denser regions.
Datashader really shines when looking at geographic information. Here are the latitudes and longitudes of our dataset plotted out, giving us a map of the city colored by density of structures:
NewYorkCity = (( 913164.0, 1067279.0), (120966.0, 272275.0))
cvs = ds.Canvas(700, 700, *NewYorkCity)
agg = cvs.points(ny, 'xcoord', 'ycoord')
view = tf.shade(agg, cmap = cm(inferno), how='log')
export(tf.spread(view, px=2), 'firery')
Interestingly, since we're looking at structures, the large buildings of Manhattan show up as less dense on the map. The densest areas measured by number of lots would be single or multi family townhomes.
Unfortunately, Datashader doesn't have the best documentation. Browse through the examples from their github repo. I would focus on the visualization pipeline and the US Census Example for the question below. Feel free to use my samples as templates as well when you work on this problem.
You work for a real estate developer and are researching underbuilt areas of the city. After looking in the Pluto data dictionary, you've discovered that all tax assessments consist of two parts: The assessment of the land and assessment of the structure. You reason that there should be a correlation between these two values: more valuable land will have more valuable structures on them (more valuable in this case refers not just to a mansion vs a bungalow, but an apartment tower vs a single family home). Deviations from the norm could represent underbuilt or overbuilt areas of the city. You also recently read a really cool blog post about bivariate choropleth maps, and think the technique could be used for this problem.
Datashader is really cool, but it's not that great at labeling your visualization. Don't worry about providing a legend, but provide a quick explanation as to which areas of the city are overbuilt, which areas are underbuilt, and which areas are built in a way that's properly correlated with their land value.
# since total = land + structure => structure = total-land
ny['assess_struct'] = ny['assesstot'] - ny['assessland']
agg = ds.Canvas().points(ny, 'xcoord', 'ycoord', ds.sum('assess_struct'))
view = tf.shade(agg,cmap = cm(inferno))
agg2 = ds.Canvas().points(ny, 'xcoord', 'ycoord', ds.sum('assessland'))
view2 = tf.shade(agg2, cmap = cm(viridis))
tf.spread(view+view2,px=2)
From the graph, it looks like bright yellow areas such as manhattan and parts of brooklyn are very developed. Blue areas, such as parts of brooklyn and queens are semi developed and Purple areas like staten island are underdeveloped.